
import globalConfig from '@/config/index.js'

/**
 * 全局请求
 * @param {*} url 
 * @param {*} method 
 * @param {*} data 
 * @param {*} config 
 */
export const request = (url, method, data, config = {}) => {
	return new Promise((resolve, reject) => {
		const storageToken = uni.getStorageSync('token')
		const token = storageToken ? {
			'access-token': storageToken
		} : ''
		uni.request({
			url: globalConfig.BASE_URL + '/v1' + url,
			method,
			data,
			header: {
				...token,
				...config.header,
			},
			success(result) {
				resolve(result.data)
			},
			fail(err) {
				reject(err)
			},
			complete(data) {
				console.log(data)
				if (data.data.code === 10000) {
					// 未登录
					uni.showToast({
						title: data.data.msg,
						icon: 'none'
					})
					uni.reLaunch({
						url: '/pages/login/index'
					})
				}
			}
		})
	})
}

/**
 * @title 上传文件
 */
export const httpFile = (url, filePath) => {
	return new Promise((resolve, reject) => {
		const storageToken = uni.getStorageSync('token')
		const token = storageToken ? {
			'access-token': storageToken
		} : ''

		uni.uploadFile({
			url: 'https://appapi.zgszys.cn/v1' + url,
			filePath,
			name: 'file',
			header: {
				...token,
			},
			success(res) {
				resolve(JSON.parse(res.data))
			},
			fail(err) {
				reject(err)
			}
		})
	})
}


/**
 * GET请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} config 
 */
export const httpGet = (url, data = {}, config) => {
	return request(url, 'GET', data, config)
}

/**
 * POST请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} config 
 */
export const httpPost = (url, data = {}, config) => {
	return request(url, 'POST', data, config)
}

/**
 * PUT请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} config 
 */
export const httpPut = (url, data = {}, config) => {
	return request(url, 'PUT', data, config)
}


/**
 * DELETE请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} config 
 */

export const httpDelete = (url, data = {}, config) => {
	return request(url, 'DELETe', data, config)
}
